/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yang
 * Date: 2022-09-22
 * Time: 15:19
 */
public class MyBlockingQueue {
    int maxSize = 1000;
    int[] elements = new int[maxSize];
    int usedSize = 0;
    int head = 0;
    int rear = 0;

    void put(int num) throws InterruptedException {
        synchronized (this){
            while(usedSize == maxSize){
                this.wait();
            }

            elements[rear++] = num;
            usedSize++;
            if(rear >= maxSize)rear = 0;

            this.notify();
        }
    }

    int take() throws InterruptedException {
        synchronized (this){
            while(usedSize == 0){
                this.wait();
            }

            usedSize--;
            int ret = elements[head++];
            if(head >= maxSize)head = 0;
            this.notify();
            return ret;
        }
    }


    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue q = new MyBlockingQueue();
        q.put(1);
        q.put(2);
        System.out.println(q.take());
        System.out.println(q.take());
    }
}
